package com.maimang.platform.common.service.impl;

import com.maimang.platform.annotation.DataScope;
import com.maimang.platform.common.entity.*;
import com.maimang.platform.common.mapper.*;
import com.maimang.platform.common.service.SysUserService;
import com.maimang.platform.common.utils.UserUtil;
import com.maimang.platform.common.utils.encryption.Md5Utils;
import com.maimang.platform.constant.UserConstants;
import com.maimang.platform.exception.BusinessException;
import com.maimang.platform.lang.ConvertUtils;
import com.maimang.platform.lang.StringUtils;
import com.maimang.platform.shiro.service.SysPasswordService;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户 业务层处理
 *
 * @author Rocky
 */
@Service
public class SysUserServiceImpl implements SysUserService {
	private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
	@Autowired
	private SysUserMapper userMapper;

	@Autowired
	private SysRoleMapper roleMapper;

	@Autowired
	private SysPostMapper postMapper;

	@Autowired
	private SysUserPostMapper userPostMapper;

	@Autowired
	private SysUserRoleMapper userRoleMapper;

	@Autowired
	private SysDeptMapper sysDeptMapper;

	@Autowired
	private SysUserDeptMapper userDeptMapper;

	@Autowired
	private SysPasswordService passwordService;

	/**
	 * 根据条件分页查询用户对象
	 *
	 * @param user 用户信息
	 * @return 用户信息集合信息
	 */
	@Override
	@DataScope(tableAlias = "u")
	public List<SysUser> selectUserList(SysUser user) {
		return userMapper.selectUserList(user);
	}

	/**
	 * 根据条件分页查询用户对象
	 *
	 * @param sysUser 用户信息
	 * @return 用户信息集合信息
	 */
	@Override
	public List<SysUser> selectUserListDept(SysUser sysUser) {
		return userMapper.selectUserListDept(sysUser);
	}

	/**
	 * 通过用户名查询用户
	 *
	 * @param userName 用户名
	 * @return 用户对象信息
	 */
	@Override
	public SysUser selectUserByLoginName(String userName) {
		return userMapper.selectUserByLoginName(userName);
	}

	/**
	 * 通过第三方(钉钉)id查询用户
	 *
	 * @param unionid 用户在当前开放应用所属企业内的唯一标识
	 * @param openId  用户在当前开放应用内的唯一标识
	 * @return
	 */
	@Override
	public SysUser selectUserByUnionid(String unionid, String openId) {
		return userMapper.selectUserByUnionid(unionid, openId);
	}

	/**
	 * 通过userid查询用户
	 *
	 * @param userid 第三方用户id
	 * @return
	 */
	@Override
	public SysUser selectUserByUserid(@Param(value = "userid") String userid) {
		return userMapper.selectUserByUserid(userid);
	}

	/**
	 * 通过手机号码查询用户
	 *
	 * @param phoneNumber 手机号码
	 * @return 用户对象信息
	 */
	@Override
	public SysUser selectUserByPhoneNumber(String phoneNumber) {
		return userMapper.selectUserByPhoneNumber(phoneNumber);
	}

	/**
	 * 通过邮箱查询用户
	 *
	 * @param email 邮箱
	 * @return 用户对象信息
	 */
	@Override
	public SysUser selectUserByEmail(String email) {
		return userMapper.selectUserByEmail(email);
	}

	/**
	 * 通过用户ID查询用户
	 *
	 * @param userId 用户ID
	 * @return 用户对象信息
	 */
	@Override
	public SysUser selectUserById(Long userId) {
		return userMapper.selectUserById(userId);
	}

	/**
	 * 通过用户ID删除用户
	 *
	 * @param userId 用户ID
	 * @return 结果
	 */
	@Override
	public int deleteUserById(Long userId) {
		// 删除用户与角色关联
		userRoleMapper.deleteUserRoleByUserId(userId);
		// 删除用户与岗位表
		userPostMapper.deleteUserPostByUserId(userId);
		return userMapper.deleteUserById(userId);
	}

	/**
	 * 批量删除用户信息
	 *
	 * @param ids 需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteUserByIds(String ids) throws Exception {
		Long[] userIds = ConvertUtils.toLongArray(ids);
		for (Long userId : userIds) {
			if (SysUser.isAdmin(userId)) {
				throw new BusinessException("不允许删除超级管理员用户");
			}
		}
		return userMapper.deleteUserByIds(userIds);
	}

	/**
	 * 新增保存用户信息
	 *
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	public int insertUser(SysUser user) {
		// 新增用户信息
		int rows = userMapper.insertUser(user);
		// 新增用户岗位关联
		insertUserPost(user);
		// 新增用户与角色管理
		insertUserRole(user);
		// 新增用户与部门关联
		insertUserDept(user);
		return rows;
	}

	/**
	 * 修改保存用户信息
	 *
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	public int updateUser(SysUser user) {
		Long userId = user.getUserId();
		// 删除用户与角色关联
		userRoleMapper.deleteUserRoleByUserId(userId);
		// 新增用户与角色管理
		insertUserRole(user);
		// 删除用户与岗位关联
		userPostMapper.deleteUserPostByUserId(userId);
		// 新增用户与岗位管理
		insertUserPost(user);
		// 删除用户与部门关联
		// userDeptMapper.deleteSysUserDeptById(userId);
		// 新增用户与部门关联
		insertUserDept(user);
		return userMapper.updateUser(user);
	}

	/**
	 * 修改用户个人详细信息
	 *
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	public int updateUserInfo(SysUser user) {
		return userMapper.updateUser(user);
	}

	/**
	 * 修改用户密码
	 *
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	public int resetUserPwd(SysUser user) {
		return updateUserInfo(user);
	}

	/**
	 * 新增用户角色信息
	 *
	 * @param user 用户对象
	 */
	public void insertUserRole(SysUser user) {
		Long[] roles = user.getRoleIds();
		if (StringUtils.isNotNull(roles)) {
			// 新增用户与角色管理
			List<SysUserRole> list = new ArrayList<SysUserRole>();
			for (Long roleId : roles) {
				SysUserRole ur = new SysUserRole();
				ur.setUserId(user.getUserId());
				ur.setRoleId(roleId);
				list.add(ur);
			}
			if (list.size() > 0) {
				userRoleMapper.batchUserRole(list);
			}
		}
	}

	/**
	 * 新增用户部门信息
	 *
	 * @param user
	 */
	public void insertUserDept(SysUser user) {
		Long[] deptIds = user.getDeptIds();
		if (StringUtils.isNotNull(deptIds)) {
			// 新增用户与部门管理
			for (Long deptId : deptIds) {
				if (!UserUtil.isSaleManager(user.getUserName())) {
					SysUserDept userDept = new SysUserDept();
					userDept.setUserId(user.getUserId());
					userDept.setDeptId(deptId);
					userDeptMapper.insertSysUserDept(userDept);
				}
			}
		}
	}

	/**
	 * 新增用户岗位信息
	 *
	 * @param user 用户对象
	 */
	public void insertUserPost(SysUser user) {
		Long[] posts = user.getPostIds();
		if (StringUtils.isNotNull(posts)) {
			// 新增用户与岗位管理
			List<SysUserPost> list = new ArrayList<SysUserPost>();
			for (Long postId : posts) {
				SysUserPost up = new SysUserPost();
				up.setUserId(user.getUserId());
				up.setPostId(postId);
				list.add(up);
			}
			if (list.size() > 0) {
				userPostMapper.batchUserPost(list);
			}
		}
	}

	/**
	 * 校验用户名称是否唯一
	 *
	 * @param loginName 用户名
	 * @return
	 */
	@Override
	public String checkLoginNameUnique(String loginName) {
		int count = userMapper.checkLoginNameUnique(loginName);
		if (count > 0) {
			return UserConstants.USER_NAME_NOT_UNIQUE;
		}
		return UserConstants.USER_NAME_UNIQUE;
	}

	/**
	 * 校验用户名称是否唯一
	 *
	 * @param user 用户信息
	 * @return
	 */
	@Override
	public String checkPhoneUnique(SysUser user) {
		Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
		SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
		if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
			return UserConstants.USER_PHONE_NOT_UNIQUE;
		}
		return UserConstants.USER_PHONE_UNIQUE;
	}

	/**
	 * 校验email是否唯一
	 *
	 * @param user 用户信息
	 * @return
	 */
	@Override
	public String checkEmailUnique(SysUser user) {
		Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
		SysUser info = userMapper.checkEmailUnique(user.getEmail());
		if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
			return UserConstants.USER_EMAIL_NOT_UNIQUE;
		}
		return UserConstants.USER_EMAIL_UNIQUE;
	}

	/**
	 * 查询用户所属角色组
	 *
	 * @param userId 用户ID
	 * @return 结果
	 */
	@Override
	public String selectUserRoleGroup(Long userId) {
		List<SysRole> list = roleMapper.selectRolesByUserId(userId);
		StringBuffer idsStr = new StringBuffer();
		for (SysRole role : list) {
			idsStr.append(role.getRoleName()).append(",");
		}
		if (StringUtils.isNotEmpty(idsStr.toString())) {
			return idsStr.substring(0, idsStr.length() - 1);
		}
		return idsStr.toString();
	}

	/**
	 * 查询用户所属岗位组
	 *
	 * @param userId 用户ID
	 * @return 结果
	 */
	@Override
	public String selectUserPostGroup(Long userId) {
		List<SysPost> list = postMapper.selectPostsByUserId(userId);
		StringBuffer idsStr = new StringBuffer();
		for (SysPost post : list) {
			idsStr.append(post.getPostName()).append(",");
		}
		if (StringUtils.isNotEmpty(idsStr.toString())) {
			return idsStr.substring(0, idsStr.length() - 1);
		}
		return idsStr.toString();
	}

	/**
	 * 获取用户组织树信息
	 *
	 * @param userIds
	 * @return
	 */
	@Override
	public List<Map<String, Object>> userTreeData(String userIds) {
		List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
		List<SysDept> deptList = sysDeptMapper.selectDeptList(new SysDept());
		List<SysUser> sysUsers = userMapper.selectUserList(new SysUser());
		if (StringUtils.isNotNull(userIds)) {
			List userIdList = Arrays.asList(userIds.split(","));
			Set<Long> userDepts = new HashSet<>();
			for (SysUser sysUser : sysUsers) {
				if (userIdList.contains(sysUser.getUserId())) {
					List<SysUserDept> userDeptList = userDeptMapper.selectSysUserDeptById(sysUser.getUserId());
					for (SysUserDept sysUserDept : userDeptList) {
						userDepts.add(sysUserDept.getDeptId());
					}
				}
			}
			trees = getTrees(deptList, sysUsers, true, userDepts, userIdList);
		} else {
			trees = getTrees(deptList, sysUsers, false, null, null);
		}
		return trees;
	}

	/**
	 * 对象转部门树
	 *
	 * @param deptList  部门列表
	 * @param sysUsers  用户
	 * @param isCheck   是否需要选中
	 * @param userDepts 部门已存在菜单列表
	 * @return
	 */
	public List<Map<String, Object>> getTrees(List<SysDept> deptList, List<SysUser> sysUsers, boolean isCheck, Set<Long> userDepts, List userIdList) {

		List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
		for (SysDept dept : deptList) {
			if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
				Map<String, Object> deptMap = new HashMap<String, Object>();
				deptMap.put("id", dept.getDeptId());
				deptMap.put("pId", dept.getParentId());
				deptMap.put("name", dept.getDeptName());
				deptMap.put("title", "dept");
				if (isCheck) {
					deptMap.put("checked", userDepts.contains(dept.getDeptId()));
				} else {
					deptMap.put("checked", false);
				}
				trees.add(deptMap);
			}
		}
       /* for (SysUser sysUser : sysUsers) {
            if (UserConstants.NORMAL.equals(sysUser.getStatus())) {
                Map<String, Object> deptMap = new HashMap<String, Object>();
                deptMap.put("id", sysUser.getUserId());
                deptMap.put("pId", sysUser.getDeptId());
                deptMap.put("name", sysUser.getUserName());
                deptMap.put("title", "user");
                if (isCheck) {
                    deptMap.put("checked", userIdList.contains(sysUser.getUserId()));
                } else {
                    deptMap.put("checked", false);
                }
                trees.add(deptMap);
            }
        }*/
		return trees;
	}

	/**
	 * 导入用户数据
	 *
	 * @param userList        用户数据列表
	 * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
	 * @param operName        操作用户
	 * @param password        初始密码
	 * @return 结果
	 */
	@Override
	public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName, String password) {
		if (StringUtils.isNull(userList) || userList.size() == 0) {
			throw new BusinessException("导入用户数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		for (SysUser user : userList) {
			try {
				// 验证是否存在这个用户
				SysUser u = userMapper.selectUserByLoginName(user.getLoginName());
				if (StringUtils.isNull(u)) {
					user.setPassword(Md5Utils.hash(user.getLoginName() + password));
					user.setPassword(passwordService.encryptPassword(user.getLoginName(), password, user.getSalt()));
					user.setCreateUser(operName);
					this.insertUser(user);
					successNum++;
					successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 导入成功");
				} else if (isUpdateSupport) {
					user.setUpdateUser(operName);
					this.updateUser(user);
					successNum++;
					successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 更新成功");
				} else {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、账号 " + user.getLoginName() + " 已存在");
				}
			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、账号 " + user.getLoginName() + " 导入失败：";
				failureMsg.append(msg + e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new BusinessException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}

	/**
	 * 用户状态修改
	 *
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	public int changeStatus(SysUser user) {
		if (SysUser.isAdmin(user.getUserId())) {
			throw new BusinessException("不允许修改超级管理员用户");
		}
		return userMapper.updateUser(user);
	}
}
